#include "lister.h"

int main(int argc, char *argv[])
{
	FILE *in;		// Declare file pointer
	char source_file[MAX_FILE_NAME_LENGTH] = {'\0'};
	char source_buffer[MAX_SOURCE_LINE_LENGTH];
	int line_number = 1;
  int page_number = 1;

	if (argc < 2){		// Check for input file
		fprintf(stderr, "Usage: %s filename\n", argv[0]);
		return 0;
	}

	if ((in = init_lister(argv[1])) == NULL)	// Open file
		return 0;

	while (get_source_line(in, source_buffer, line_number)) {
		if (line_number > MAX_LINES_PER_PAGE) {
      page_number++;
			print_page_header(page_number);
			line_number = 1;
      printf("%d: %s", line_number, source_buffer);
		}
		else {
		printf("%d: %s", line_number, source_buffer);
		line_number++;
		}
	}
	
	return 0;
}

FILE *init_lister(char file[]) {
	
	FILE *input;
	if ((input = fopen(file, "r")) == NULL) {    // If error opening the file
		fprintf(stderr, "Error opening file.\n");	// Handle 
		return input;
	}
	else {   //Success opening file results in printing of time and info of the file
		time_t now;
		time(&now);
		printf("Page\t1\t%s\n", asctime(localtime(&now)));
		return input;
	}
	
 
}

BOOLEAN get_source_line(FILE *fpt, char source_buffer[], int line_number) {   // Checks to make sure it got the source_line
	
	if(fgets(source_buffer, MAX_SOURCE_LINE_LENGTH, fpt) == NULL) {
		return FALSE;
	}
	else{
		return TRUE;
	}
}


void print_page_header(int page_number) {                              // quick and dirty way to print the header. Need to modify it to reflect the page number
	time_t now;
	time(&now);
	printf("Page\t%d\t%s\n", page_number, asctime(localtime(&now)));
}
//Reviewed by Ariana Griego
//Reviewed by Daniel Ortiz
//Reviewed by Hao Zhang, everything looks great to me.